﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;
using System.Net;
using CommandLine;

namespace CmdHttpRequest
{
    internal sealed class Program
    {

        private sealed class Options
        {
            [Option("u", "url",
                    Required = true,
                    HelpText = "URL to check")]
            public string url = String.Empty;

            [Option("d", "dir",
                    Required = false,
                    HelpText = "Output directory")]
            public string outputDirectory = String.Empty;

            [Option("t", "text",
                    Required = false,
                    HelpText = "Text to check for")]
            public string text = String.Empty;

            [Option("o", "timeout",
                    Required = false,
                    HelpText = "Timeout (in milliseconds)")]
            public int timeout = 0;

            [ValueList(typeof(List<string>))]
            public IList<string> DefinitionFiles = null;

            [HelpOption]
            public string GetUsage()
            {
                HelpText info = new HelpText("CmdHttpRequest");
                info.Copyright = new CopyrightInfo("Don Kitchen", DateTime.Now.Year);
                info.AddLicenseLine("This is free software. You may redistribute copies of it under the terms of");
                info.AddLicenseLine("the MIT License <http://www.opensource.org/licenses/mit-license.php>.");

                info.AddUsageLine("Usage: CmdHttpRequest -u http://www.google.com");
                info.AddUsageLine("Usage: CmdHttpRequest -u http://www.google.com -d c:\\temp");
                info.AddUsageLine("Usage: CmdHttpRequest -u http://www.google.com -t Success");
                info.AddUsageLine("Usage: CmdHttpRequest -u http://www.google.com -o 60000");
                info.AddOptions(this);
                return info;
            }
        }

        static void Main(string[] args)
        {

            Options options = new Options();

            if (Parser.ParseArguments(args, options, Console.Out))
            {

                if (options.url.Length == 0)
                {
                    Console.WriteLine("URL to check must be provided.");
                    Environment.Exit(1);
                }

                try
                {
                    // Create a request for the URL.         
                    WebRequest request = WebRequest.Create(options.url);                    

                    // If a timeout was provided, use it
                    if (options.timeout > 0)
                    {
                        request.Timeout = options.timeout;
                    }
                    
                    // If required by the server, set the credentials.
                    request.Credentials = CredentialCache.DefaultCredentials;

                    // Get the response.
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                    // Display the status.
                    Console.WriteLine(string.Format("Status Code: {0}", response.StatusDescription));

                    // Get the stream containing content returned by the server.
                    Stream dataStream = response.GetResponseStream();

                    // Open the stream using a StreamReader for easy access.
                    StreamReader reader = new StreamReader(dataStream);

                    // Read the content.
                    string responseFromServer = reader.ReadToEnd();

                    // Check to see if keyword is in results
                    if (options.text.Length > 0)
                    {
                        Console.Write(string.Format("Keyword '{0}' was ", options.text));
                        if (!responseFromServer.Contains(options.text))
                        {
                            Console.Write("not ");
                        }
                        Console.WriteLine("found.");
                    }

                    // Save the content to a file if instructed to do so
                    if (options.outputDirectory.Length > 0)
                    {
                        string fileName = string.Format("{0}\\{1} {2}.htm", options.outputDirectory,
                                                                            request.RequestUri.Host,
                                                                            DateTime.Now.ToString("MM-dd-yy HH-mm-ss"));
                        try
                        {
                            TextWriter tw = new StreamWriter(fileName);
                            tw.WriteLine(responseFromServer);
                            tw.Close();

                            Console.WriteLine(string.Format("File successfully saved to {0}", fileName));

                        }
                        catch (System.IO.IOException ex)
                        {
                            Console.WriteLine(ex.Message.ToString());
                        }

                    }

                    // Cleanup the streams and the response.
                    reader.Close();
                    dataStream.Close();
                    response.Close();
                }
                catch (System.UriFormatException ex)
                {
                    Console.WriteLine(ex.Message.ToString());
                    Console.WriteLine("Invalid URL format.  Please use http://www.yoursite.com");
                }
                catch (System.Net.WebException ex)
                {
                    Console.WriteLine(ex.Message.ToString());
                }
            }

            Environment.Exit(0);
        }
    }
}
